package com.loveprogrammer.handler;

import com.alibaba.fastjson2.JSON;
import com.loveprogrammer.base.network.support.BaseHandler;
import com.loveprogrammer.base.bean.session.Session;
import com.loveprogrammer.common.SessionGameContext;
import com.loveprogrammer.base.network.support.SessionManager;
import com.loveprogrammer.command.anotation.TagListener;
import com.loveprogrammer.command.anotation.TopicListener;
import com.loveprogrammer.command.server.ServerLoginOrRegisterTag;
import com.loveprogrammer.command.server.ServerTopic;
import com.loveprogrammer.constants.CommonValue;
import com.loveprogrammer.convert.JobTemplateConvert;
import com.loveprogrammer.dto.job.JobChoose;
import com.loveprogrammer.dto.login.UserLogin;
import com.loveprogrammer.dto.login.UserRegister;
import com.loveprogrammer.domain.User;
import com.loveprogrammer.exception.ServerException;
import com.loveprogrammer.factory.JobFactory;
import com.loveprogrammer.factory.template.JobTemplate;
import com.loveprogrammer.model.game.UserGameWrapper;
import com.loveprogrammer.pojo.StringMessage;
import com.loveprogrammer.service.IUserService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName LoginHandler
 * @Description 登录
 * @Author admin
 * @Date 2024/2/6 15:49
 * @Version 1.0
 */
@Component
@TopicListener(topic = ServerTopic.TOPIC_LOGIN)
public class LoginHandler extends BaseHandler {

    public static final Logger log = LoggerFactory.getLogger(LoginHandler.class);

    @Autowired
    private IUserService userService;

    /***
     * 注册
     * @param ctx
     * @param register
     */
    @TagListener(tag = ServerLoginOrRegisterTag.TAG_LOGIN_REGISTER,messageClass = UserRegister.class)
    public StringMessage register(ChannelHandlerContext ctx, UserRegister register) throws ServerException {
        log.info("数据内容：data=" + JSON.toJSONString(register));

        User user = userService.findUserByNickname(register.getName());
        if(user == null) {
            user = new User();
            user.setNickName(register.getName());
            user.setPassword("111111");
            user.setAccount(register.getName());
            userService.save(user);
            // 登录成功，把user信息放入session中
            Session session = SessionManager.getInstance().getSessionByChannel(ctx.channel());
            session.setUserId(user.getId().toString());
            session.setNickname(user.getNickName());
            // 创建用户的游戏数据并写入全局缓存中
            UserGameWrapper gameWrapper = UserGameWrapper.create(user);
            SessionGameContext.USER_GAME_MAP.put(user.getId(),gameWrapper);

            // 跳转到选择职业界面
            StringMessage data = StringMessage.create(register.getSuccessCallbackTopic(), register.getSuccessCallbackTag());
            data.setStatusCode(CommonValue.MSG_STATUS_CODE_SUCCESS);
            // 获得可用的职业
            List<JobTemplate> jobTemplates = JobFactory.getTemplates();
            JobChoose jobChoose = new JobChoose(data);
            jobChoose.setJobList(JobTemplateConvert.INSTANCE.toJobChooseItems(jobTemplates));
            data.setBody(JSON.toJSONString(jobChoose));
            return data;
        }
        else{
            log.warn("用户已经存在");
            throw new ServerException("用户已经存在");
        }
    }

    /***
     * 登录
     * @param ctx
     * @param register
     */
    @TagListener(tag = ServerLoginOrRegisterTag.TAG_LOGIN_LOGIN,messageClass = UserLogin.class)
    public StringMessage login(ChannelHandlerContext ctx, UserLogin register) throws ServerException {
        //  查询用户
        User user = userService.findUserByAccount(register.getUserName());
        if(user == null) {
            throw new ServerException("用户不存在");
        }
        // 对比密码
        if(!register.getPassword().equalsIgnoreCase(user.getPassword())) {
            throw new ServerException("用户名密码不匹配");
        }
        // 登录成功，把user信息放入session中
        Session session = SessionManager.getInstance().getSessionByChannel(ctx.channel());
        session.setUserId(user.getId().toString());
        session.setNickname(user.getNickName());

        // TODO 这里应该是先读取用户的数据而不是创建新的
        UserGameWrapper gameWrapper = UserGameWrapper.create(user);
        SessionGameContext.USER_GAME_MAP.put(user.getId(),gameWrapper);

        // 客户端进入选择英雄页面
        StringMessage message = StringMessage.create(register.getSuccessCallbackTopic(), register.getSuccessCallbackTag());
        message.setStatusCode(CommonValue.MSG_STATUS_CODE_SUCCESS);
        // 获得可用的职业
        List<JobTemplate> jobTemplates = JobFactory.getTemplates();
        JobChoose jobChoose = new JobChoose(message);
        jobChoose.setJobList(JobTemplateConvert.INSTANCE.toJobChooseItems(jobTemplates));
        message.setBody(JSON.toJSONString(jobChoose));
        return message;
    }
}
